package com.aichat.ai_chatbackend.service.impl;

import com.aichat.ai_chatbackend.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 邮件发送服务实现类
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public boolean sendVerificationCode(String to, String code) {
        String subject = "【智能陪聊助手】邮箱验证码";
        String content = String.format(
            "您好！\n\n" +
            "您正在注册智能陪聊助手账户，您的邮箱验证码是：\n\n" +
            "【 %s 】\n\n" +
            "验证码有效期为5分钟，请及时使用。\n" +
            "如果这不是您本人的操作，请忽略此邮件。\n\n" +
            "祝您使用愉快！\n" +
            "智能陪聊助手团队", 
            code
        );
        
        return sendSimpleEmail(to, subject, content);
    }

    @Override
    public boolean sendSimpleEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            log.info("邮件发送成功，收件人：{}", to);
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败，收件人：{}，错误信息：{}", to, e.getMessage(), e);
            return false;
        }
    }
} 